package com.netty.common.protocol;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
/**
 * 数据包格式为：int(数据长度)+数据
 * 解码
 * @author dwjf321
 *
 */
public class RpcDecoder extends ByteToMessageDecoder{
	
	private Class<?> genericClass;
	
	public RpcDecoder(Class<?> genericClass){
		this.genericClass = genericClass;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) throws Exception {
		//数据小于4
		if (in.readableBytes() < 4) {
			return;
		}
		//标记读取位置
		in.markReaderIndex();
		//数据长度
		int dateLength = in.readInt();
		if (in.readableBytes() < dateLength) {
			in.resetReaderIndex();
			return;
		}
		//把数据读取到data中
		byte[] data = new byte[dateLength];
		in.readBytes(data);
		//反序列化出对象
		Object obj = SerializationUtil.deserializer(data, genericClass);
		out.add(obj);
	}

}
